<template>
  <div class="survey" v-loading="loading">
    <div class="top">
      <div class="search">
        <div class="contition">
          <div class="wrap_time">
            <date-time type="other_half_hour" :query="query" @isFold="isShowFold" :isTimePeriod = "true"></date-time>
            <el-button type="primary" class="primary_btn fr find" @click.stop='search'>{{$t('public.search2')}}</el-button>
            <div class="clear"></div></div>
          <div class="wrap_drop">
            <unfold :isShow="isFold" :title="[]">
              <template slot="unfoldSlot">
                <div class="skill">
                  <span class="ski">{{$t('call.callType')}} : </span>
                  <el-select size="mini"
                             v-model.trim="value"
                             :placeholder="$t('webchat.webchatAll')" multiple>
                    <el-option
                      v-for="item in options"
                      :label="item.label"
                      :value="item.value"
                      :key="item.value">
                    </el-option>
                  </el-select>
                </div>
              </template>
            </unfold>
          </div>
        </div>
      </div>
      <affix :label="$t('report.imReportBusinessAnalyse')"></affix>
    </div>
    <div :id="id">
      <el-row class="ichars">
        <highcharts :options="options24out"></highcharts>
        <!-- <div class="notes">
          <span class="light">{{$t('report.hicharsNotes')}}: <span></span>{{$t('report.hicharsLight')}}</span>
          <span class="dark"><span></span>{{$t('report.hicharsDark')}}</span>
        </div> -->
      </el-row>
      <div class="tab">
        <div class="export">
          <!-- <el-button class="primary_btn fr report_excel_btn"
            v-if="$store.getters.exportFromEnd"
            v-on:click="exportExcel"
          >{{$t('report.exportXls')+($store.state.xlsxExportMode==='Both'?'(旧)':'')}}</el-button> -->

          <el-button class="primary_btn fr report_excel_btn"
            v-on:click="exportXlsx"
          >{{$t('report.exportXls')}}</el-button>
          <el-button class="primary_btn fr pdf" v-on:click="exportPdf">{{$t('report.exportPDF')}}</el-button>
        </div>
        <report-table :data="tableData" :sum="totalData" :config="headOptions.Config"> </report-table>
      </div>
    </div>
    <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :title="$t('report.reportExportHelp')" :visible.sync="dialogVisible" width="30%">
      <span>{{$t('report.reportExportTipTitle')}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button class="primary_btn" @click="dialogVisible = false">{{$t('public.cancel')}}</el-button>
        <el-button class="primary_btn" type="primary" @click="confirm">{{$t('public.confirm')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import affix from '../../../ui-modules/affix/Affix.vue'
  import unfold from '../../../ui-modules/unfold/index.vue'
  import dateTime from '../base/datetime.vue'
  import {exportReportPdf, checkTime, searchTime, headOptionsToXlsxHeaders, getCallLabelReportKeys} from '@/utils/reportUtils.js'
  import {deepClone} from '@/utils/m7Utils.js'
  import reportTable from '../base/reportTable.vue'
  import * as XlsxUtil from 'src/utils/XlsxUtil.umd.js'
  // import { parseFormulaStr, dal2Rpn, STATUS, evalRpn, toNumber } from '../base/formulaUtil.js'
  export default {
    name: 'survey',
    data () {
      return {
        allKeyLabels: {},
        isFold: false, // 是否展示搜索条件
        loading: false,
        id: 'call_label_report', // 查询id
        query: {},
        agents: [], // 渲染座席数据
        value: [], // 呼叫类型绑定值
        dialogVisible: false, // 导出pdf弹窗开关值
        options: [ // 呼叫类型渲染数据
          {label: this.$t('qualityCheck.normalCallIn'), value: 'normal'},
          {label: this.$t('qualityCheck.callOut'), value: 'dialout'},
          {label: this.$t('qualityCheck.callInTrans'), value: 'transfer'},
          {label: this.$t('qualityCheck.callOutTrans'), value: 'dialTransfer'},
        ],
        sum: [], // 合计变量
        headOptions: { // 表头数据
          Config: []
        },
        options24out: {
          color: ['#f00', '#ff0'],
          chart: {
            type: 'column'
          },
          title: {
            text: this.$t('report.callTagStatistics')
          },
          xAxis: {
            type: 'category',
            labels: {
              rotation: -45  // 设置轴标签旋转角度
            }
          },
          yAxis: {
            min: 0,
            title: {
              text: ''
            }
          },
          legend: {
            enabled: false
          },
          tooltip: {
            pointFormat: this.$t('report.callTagNum') + ': <b>{point.y}' + this.$t('report.callTagOrder') + '</b>'
          },
          credits: { enabled: false },
          series: [{
            name: '',
            data: [],
            // dataLabels: {
            //   enabled: true,
            //   rotation: -90,
            //   color: '#FFFFFF',
            //   align: 'right',
            //   format: '{point.y}', // :.1f 为保留 1 位小数
            //   y: 10
            // }
          }]
        },
        serveNumData: [] // 表格数据
      }
    },
    components: {
      affix,
      unfold,
      dateTime,
      reportTable
    },
    computed: {
      tableData () {
        return this.getTableData(this.serverData, this.headOptions)
      },
      totalData () {
        return this.getTotalData(this.serverData, this.headOptions)
      },
    },
    methods: {
      // 是否展开收起查询条件
      isShowFold (bool) {
        this.isFold = bool
      },
      getTableData (serverData) {
        if (!serverData || serverData.length === 0) {
          return []
        }
        let data = deepClone(serverData)
        const allKeyLabels = this.allKeyLabels || {}
        data.forEach(item => {
          item.Label = allKeyLabels !== {} ? allKeyLabels[item.Label]: ''
        })
        return data
      },
      getTotalData (serverData, headOptions) {
        if (!serverData || serverData.length === 0) {
          return [{Label: this.$t('report.total')}]
        }

        let headerConfig = headOptions.Config || []
        let datas = serverData
        let total = { Label: this.$t('report.total') }

        for (let i = 0; i < headerConfig.length; i++) {
          for (let j = 0; j < datas.length; j++) {
            if (!isNaN(datas[j][headerConfig[i].name])) {
              if ((headerConfig[i].name in total) === false) {
                total[headerConfig[i].name] = 0
              }
              total[headerConfig[i].name] += datas[j][headerConfig[i].name]
            }
          }
        }

        return [total]
      },
      dealCharts (data) {
        let series = []
        const allKeyLabels = this.allKeyLabels || {}
        data.forEach((item) => {
          series.push([allKeyLabels !== {} ? allKeyLabels[item.Label]: '', item.Count])
        })
        this.options24out.series[0].data = series
      },
      getSearchQueryData (isExport) {
        let query = deepClone(this.query)
        if (query.timeType === 'other_half_hour') {
          let message = checkTime(query.StartTime, query.EndTime, false, false) // 校验类型与时间
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        let data = {
          reportType: this.id,
          account: this.$store.state.session.user.account,
          query: { reportType: this.id, callType: this.value }
        }
        if (!isExport === true) {
          //  图表标题 加入 定时段的 时间
          let highchartsTitle = ''
          if (query.timePeriod) {
            let timePeriodStartStr = query.timePeriodStart || '00:00'
            let timePeriodEndStr = query.timePeriodEnd || '23:59'
            highchartsTitle = '(' + timePeriodStartStr + '~' + timePeriodEndStr + ')'
          }
          this.options24out.title.text = this.$t('report.callTagStatistics') + highchartsTitle
        }
        data.query = Object.assign({}, data.query, query)
        // 时间插件返回的是小写的timeType转大写的
        data.query.TimeType = data.query.timeType
        delete data.query.timeType
        return data
      },
      // 查询数据的方法
      search () {
        var data = this.getSearchQueryData()
        if (!data) {
          return
        }
        // this.loading = true
        this.$store.dispatch('queryCallLabelReport', data).then((res) => {
          if (this.$store.state.report.customExportData) {
            res = JSON.parse(this.$store.state.report.customExportData)
          }
          this.serverData = deepClone(res.data)
          this.headOptions = res.tableHeader || []
          this.dealCharts(res.data)
        })
      },
      // 导出表格数据执行的方法(前端)
      exportXlsx () {
        var data = this.getSearchQueryData(true)
        if (!data) {
          return
        }

        this.loading = true
        this.$store.dispatch('queryCallLabelReport', data).then((res) => {
          if (this.$store.state.report.customExportData) {
            res = JSON.parse(this.$store.state.report.customExportData)
          }
          this.loading = false
          var headOptions = res.tableHeader
          var serverData = res.data
          var sum = []
          if (serverData.length !== 0) {
            sum = this.getTotalData(serverData, headOptions)
          }
          var tableData = this.getTableData(serverData).concat(sum);
          console.log(tableData);
          let finishLevelNum = 1 // 定义层级
          // 判断共有多少层级
          for (let i = 0; i < tableData.length; i++) {
            let item = tableData[i];
            item['Label'] = item['Label']
            let consultTypeArr = item.Label?item.Label.split('->'):[]
            let currentLevel = consultTypeArr.length
            console.log(currentLevel);
            for (let j = 0; j < currentLevel; j++) {
              if(item['Label'] !== '合计'){
                item['Label' + j] = consultTypeArr[j]
              }
            }
            finishLevelNum = currentLevel > finishLevelNum ? currentLevel : finishLevelNum
          }
          let regArr = ['一', '二', '三', '四', '五','六'] // 和导出层级匹配

          // 导出分级展示
          if (headOptions.Config && headOptions.Config.length > 0) {
            for (let k = 0; k < finishLevelNum; k++) {
              headOptions.Config.splice(k+1, 0, {
                order: '0' + k,
                name: 'Label' + k,
                // displayname: this.$t('public.callLabel', {num: regArr[k]}),
                displayname: `${regArr[k]}级标签`,
                show: true
              })
            }
            headOptions.Config[0].displayname = this.$t('public.callLabel', {num: regArr[0]})
          }
          console.log(headOptions.Config);
          var headers = headOptionsToXlsxHeaders(headOptions.Config)
          console.log(headers);
          console.log(tableData);
          var dh = XlsxUtil.getDownloadHelper(headers, tableData)
          var timeStamp = XlsxUtil.dateFormat(new Date(), 'yyyy-MM-dd hh-mm-ss')
          dh.download(this.$t('report.imReportBusinessAnalyse') + timeStamp)
        })
      },
      // 关闭配置表头弹窗
      close () {
        this.isShow = false
      },
      // 导出pdf
      confirm () {
        this.dialogVisible = false
        exportReportPdf({title: this.$t('report.imReportBusinessAnalyse') + searchTime(this.query), id: this.id})
      },
      // 导出表格数据执行的方法(后端)
      exportExcel (isDetail) {
        let myQuery = deepClone(this.query)
        if (myQuery.timeType === 'other_half_hour') {
          let message = checkTime(myQuery.StartTime, myQuery.EndTime, false, false) // 校验类型与时间
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        // 初始化查询条件
        myQuery.callType = this.value
        myQuery.TimeType = myQuery.timeType
        delete myQuery.timeType
        myQuery.accountId = this.$store.state.session.user.account
        let data = {
          Method: 'exportCallLabelReport',
          Query: myQuery
        }
        this.$store.dispatch('exportCallApproveSurveyReport', data).then(() => {
        })
      },
      // 导出PDF
      exportPdf () {
        this.dialogVisible = true
      }
    },
    watch: {

    },
    beforeMount () {
      this.$store.dispatch('getCache', { type: 'callLabel' }).then(res => {
        this.allKeyLabels = getCallLabelReportKeys(res, {}) || {}
        this.search()
      })
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  .survey
    .agent_search
      .wrap_conti
        margin 14px 0 0 20px
        .ski
          margin-right 26px
        .chan_ag
          float left
          margin-right 20px
        .el-radio
          margin-right 30px
        .dept
          .el-radio
            margin-right 42px
      .tip
        cursor pointer
        display inline-block
        height 16px
        width 16px
        border 1px solid $c-main
        text-align center
        line-height 15px
        border-radius 50%
        margin 0px 0 0 6px
        .iconfont
          border none
          font-size 10px
          color $c-main
    .skill
      .el-select
        width 400px
        margin-right 16px
      .ski
        display inline-block
        width 80px
</style>
